package com.lu.base.tools;


import com.lu.base.tools.thread.CustomThreadFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * author: luqihua
 * date:2019-09-25
 * description:定时器
 **/
public class TimerTools {
    private static final String TAG = "TimerTools";
    public static final String TASK_HEARTBEAT = "task_heartbeat";
    public static final String TASK_LOGIN = "task_login";
    public static final String TASK_BIND = "task_bind";
    public static final String TASK_REPORT_STATUS = "task_report_status";

    private final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;

    private final Map<String, ScheduledFuture<?>> mTaskQueue = new HashMap<>();

    public static class HOLDER {
        private static final TimerTools sInstance = new TimerTools();
    }

    public static TimerTools getInstance() {
        return HOLDER.sInstance;
    }

    private TimerTools() {
        scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2, new CustomThreadFactory(TAG));
        scheduledThreadPoolExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
        scheduledThreadPoolExecutor.setRemoveOnCancelPolicy(true);
    }

    /**
     * 添加一个定时任务
     *
     * @param key
     * @param runnable
     * @param delay
     * @param interval
     */
    public void start(String key, Runnable runnable, long delay, long interval) {
        stopTask(key);
        ScheduledFuture<?> future = scheduledThreadPoolExecutor.scheduleWithFixedDelay(runnable, delay, interval, TimeUnit.MILLISECONDS);
        mTaskQueue.put(key, future);
    }

    /**
     * 停止指定的定时任务
     *
     * @param keys
     */
    public void stopTask(String... keys) {
        if (keys == null) return;
        for (String key : keys) {
            ScheduledFuture<?> future = mTaskQueue.get(key);
            if (future != null && !future.isCancelled()) {
                future.cancel(true);
            }
            mTaskQueue.remove(key);
        }
    }

    /**
     * 清除所有定时任务
     */
    public void clearAllTask() {
        for (String key : mTaskQueue.keySet()) {
            ScheduledFuture<?> future = mTaskQueue.get(key);
            if (future != null && !future.isCancelled()) {
                future.cancel(true);
            }
        }
        mTaskQueue.clear();
    }


    public static class ScheduleTask implements Runnable{
        public boolean isValid = true;
        @Override
        public void run() {

        }
    }
}
